package com.hcss.qywechat.jsapi.controller;

import com.alibaba.fastjson.JSONObject;
import com.hcss.common.base.BaseClass;
import com.hcss.common.exception.HcssCommonException;
import com.hcss.util.AjaxResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;

/**
 * @描述: jsapi相关接口
 * @作者: xuqian
 * @创建日期: 2018-12-19 9:51
 * @公司 浙江鸿程计算机系统有限公司
 */
@Slf4j
@RequestMapping("jsapi")
@RestController
public class JSAPIController {
    private static final String SIGNATURE_BASE_STRING_TEMPLATE = "jsapi_ticket=JSAPITICKET&noncestr=NONCESTR&timestamp=TIMESTAMP&url=URL";
    private static final String PARAM_JSAPITICKET = "JSAPITICKET";
    private static final String PARAM_NONCESTR = "NONCESTR";
    private static final String PARAM_TIMESTAMP = "TIMESTAMP";
    private static final String PARAM_URL = "URL";

    /**
     * 获取jsapi_signature
     * 参与签名的参数有四个: noncestr（随机字符串）, jsapi_ticket, timestamp（时间戳）, url（当前网页的URL， 不包含#及其后面部分）
     * 将这些参数使用URL键值对的格式 （即 key1=value1&key2=value2…）拼接成字符串string1。
     * 然后对string1作sha1加密即可。
     * @return
     */
    @GetMapping("signature")
    public AjaxResult signature(String url) {
        if (StringUtils.isBlank(url)) {
            return AjaxResult.getMissingParamResult();
        }
        String decodeURL;
        try {
            decodeURL = URLDecoder.decode(url, "utf-8");
        } catch (UnsupportedEncodingException e) {
            log.error("获取jsapi_signature出错，" + e.getMessage(), e);
            return AjaxResult.getErrorResult("获取jsapi_signature出错");
        }
        String jsapi_ticket;
        try {
            jsapi_ticket ="";
        } catch (Exception e) {
            return AjaxResult.getErrorResult(e.getMessage());
        }
        if (StringUtils.isBlank(jsapi_ticket)) {
            return AjaxResult.getErrorResult("无法获取jsapi_ticket，请联系管理员");
        }

        String timestamp = String.valueOf(System.currentTimeMillis());
        String noncestr = BaseClass.getUUIDWithoutConnector();
        String signature_base_string = SIGNATURE_BASE_STRING_TEMPLATE.replace(PARAM_JSAPITICKET, jsapi_ticket)
                .replace(PARAM_NONCESTR, noncestr).replace(PARAM_TIMESTAMP, timestamp).replace(PARAM_URL, decodeURL);
        String signature= DigestUtils.sha1Hex(signature_base_string);// sha1加密

        JSONObject data = new JSONObject();
        data.put("noncestr", noncestr);
        data.put("ticket", jsapi_ticket);
        data.put("timestamp", timestamp);
        data.put("signature", signature);
        return AjaxResult.getSuccessResult(data);
    }
}
